#include "heap.h"

void AdjustUp(HPDateType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child)
	{
		if (a[child] > a[parent])
		{
			Swap(&a[child], &a[parent]);
		}
		else
		{
			break;
		}
		child = parent;
		parent = (parent - 1) / 2;
	}
}

void AdjustDown(HPDateType* a, int n, int parent)
{
	int leftchild = parent * 2 + 1;
	while (parent < n && leftchild < n)
	{
		if (leftchild + 1 < n && a[leftchild] < a[leftchild + 1])
		{
			leftchild += 1;
		}
		if (a[parent] < a[leftchild])
		{
			Swap(&a[leftchild], &a[parent]);
		}
		else
		{
			break;
		}
		parent = leftchild;
		leftchild = parent * 2 + 1;
	}
}

void Swap(HPDateType* a, HPDateType* b)
{
	HPDateType x = *a;
	*a = *b;
	*b = x;
}

void HeapPrint(HP* php)
{
	assert(php);
    int i = 0;
	for (i = 0; i < php->size; i++)
	{
		printf("%d ",php->a[i]);
	}
	printf("\n");
}

void HeapInit(HP* php)
{
	assert(php);
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}

void HeapInitArray(HP* php, int* a, int n)
{
	assert(php);
	HeapInit(php);
    int i = 0;
	for (i = 0; i < n; i++)
	{
		HeapPush(php,a[i]);
	}
}

void HeapDestoy(HP* php)
{
	assert(php);
	free(php->a);
	php->a = NULL;
	php->capacity = 0;
	php->size = 0;
}

void HeapPush(HP* php, HPDateType x)
{
	assert(php);
	if (php->capacity == php->size)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HPDateType* tmp = (HPDateType*)realloc(php->a, sizeof(HPDateType) * newcapacity);
		if (tmp == NULL)
		{
			printf("realloc file\n");
			exit(-1);
		}
		php->a = tmp;
		php->capacity = newcapacity;
	}
	php->a[php->size] = x;
	AdjustUp(php->a,php->size);
	php->size++;
}

void HeapPop(HP* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	Swap(&(php->a[0]),&(php->a[php->size-1]));
	php->size--;
	AdjustDown(php->a, php->size, 0);
}

HPDateType HeapTop(HP* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	return php->a[0];
}

bool HeapEmpty(HP* php)
{
	assert(php);
	return php->size == 0;
}

